package com.geline.wordtool.service;

import com.geline.wordtool.domain.TableInfo;
import com.geline.wordtool.domain.TableOne;
import com.geline.wordtool.handler.TableInfoHandler;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据模板生成word
 *
 * @author: mx
 * @date: 2024-12-03 17:35
 */
@Slf4j
public class WordDocService {

    private TableInfoHandler tableInfoHandler;

    public WordDocService(TableInfoHandler tableInfoHandler){
        this.tableInfoHandler = tableInfoHandler;
    }

    /**
     * 生成doc文件
     *
     * @param xmlFile
     * @param targetDocFile
     * @param tableNameStarts  包括字符串，多个逗号分开
     * @param excludeTableChars  排除字符串，多个逗号分开
     * @throws Exception
     */
    public void toWriterDoc(String xmlFile, File targetDocFile, String tableNameStarts, String excludeTableChars) throws Exception {
        Map map = new HashMap();
        List<TableInfo> infoList = tableInfoHandler.getTableInfoList(tableNameStarts, excludeTableChars);
        List<TableOne> tableOneList = tableInfoHandler.getTableOneList(tableNameStarts, excludeTableChars);
        map.put("tableInfoList", infoList);
        map.put("tableOneList", tableOneList);
        this.toWriterDoc(xmlFile, targetDocFile, map);
        log.debug(">>> TableInfo size = {}", infoList.size());
    }

    public void toWriterDoc(String xmlFile, File targetDocFile, Map map) throws Exception {
        log.debug(">>> xmlFile = {}, targetDocFile = {}", xmlFile, targetDocFile.getAbsoluteFile());
        //1.创建配置类
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        //2.设置classpath - resource作为模板目录
        configuration.setTemplateLoader(new ClassTemplateLoader());
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template = configuration.getTemplate(xmlFile);
        Writer out = new FileWriter(targetDocFile);
        //7.输出
        template.process(map, out);
        out.close();
    }
}
